package com.ljkj.cordial.chat.presenter.response;

import android.app.Activity;

import com.google.gson.Gson;
import com.lanjiu.lib.imclient.bus.EventConstants;
import com.lanjiu.lib.imclient.bus.MessageEvent;
import com.lanjiu.lib.imclient.dto.extra.UserChatTable;
import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.lanjiu.lib.imclient.ims.IMSRequester;
import com.lanjiu.lib.imclient.ims.IMSUtils;
import com.lanjiu.pro.business.BusinessProtocolEntities;
import com.lanjiu.pro.business.BusinessProtocolMessages;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.bean.MsgType;
import com.ljkj.cordial.chat.dao.notify.ChatContentTable;
import com.ljkj.cordial.chat.dao.notify.GroupMemberTable;
import com.ljkj.cordial.chat.dao.notify.GroupTable;
import com.ljkj.cordial.chat.notify.NotificationHelper;
import com.ljkj.cordial.chat.notify.NotificationUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * 创建群
 */
public class GroupCreateProtocolResponse extends AResponseBusinessPresenter {
    @Override
    public void onResponse(Activity activity, boolean isOnScreen, String msgType, Object msg) {
        BusinessProtocolMessages.GroupCreateProtocol response = (BusinessProtocolMessages.GroupCreateProtocol) msg;
//        if (response.getAllGroupMemberVoList() != null && !response.getAllGroupMemberVoList().isEmpty()) {
//            GroupVo gvo = new GroupVo();
//            List<GroupVo.GroupMemberVo> gmvoList = new ArrayList<>();
//            for (int i = 0; i < response.getAllGroupMemberVoList().size(); i++) {
//                BusinessProtocolEntities.AllGroupMemberVO groupMemberVO = response.getAllGroupMemberVoList().get(i);
//                if (i == 0) {
//                    if (groupMemberVO.getGuestGroupId() != 0)
//                        gvo.setGroupId(groupMemberVO.getGuestGroupId());
//                    if (groupMemberVO.getRegisteredGroupId() != 0)
//                        gvo.setGroupId(groupMemberVO.getRegisteredGroupId());
//                    gvo.setGroupType(IMSUtils.userTypeAnalysis(String.valueOf(gvo.getGroupId())));
//
//                    gvo.setName(groupMemberVO.getGroupName());
//                    gvo.setRemarks(groupMemberVO.getGroupRemarks());
//                    gvo.setAmount(groupMemberVO.getAmount());
//                    gvo.setAnnouncement(groupMemberVO.getAnnouncementContent());
//
//                    // 更新群资料
//                    GroupTable groupTable = GroupTable.queryRowByGroupId(String.valueOf(gvo.getGroupId()));
//                    if (groupTable == null) groupTable = new GroupTable();
//                    groupTable.setGroupOwnerId(gvo.getOwner());
//                    groupTable.setGroupId(String.valueOf(gvo.getGroupId()));
//                    groupTable.setGroupName(gvo.getName());
//                    groupTable.setGroupType(gvo.getGroupType());
//                    groupTable.setAnnouncementContent(gvo.getAnnouncement());
//                    groupTable.setMemberCount(gvo.getAmount());
//                    GroupTable.insert(groupTable);
//                }
//                if ("Yes".equalsIgnoreCase(groupMemberVO.getGroupOwner())) {
//                    if (groupMemberVO.getGuestUserId() != 0)
//                        gvo.setOwner(String.valueOf(groupMemberVO.getGuestUserId()));
//                    if (groupMemberVO.getRegisteredUserId() != 0)
//                        gvo.setOwner(String.valueOf(groupMemberVO.getRegisteredUserId()));
//                }
//                GroupVo.GroupMemberVo gmvo = gvo.new GroupMemberVo();
//                gmvo.setGroupMemberId(groupMemberVO.getGroupMemberId());
//                if (groupMemberVO.getGuestUserId() != 0)
//                    gmvo.setMemberUserId(String.valueOf(groupMemberVO.getGuestUserId()));
//                if (groupMemberVO.getRegisteredUserId() != 0)
//                    gmvo.setMemberUserId(String.valueOf(groupMemberVO.getRegisteredUserId()));
//                gmvo.setMemberUserType(IMSUtils.userTypeAnalysis(gmvo.getMemberUserId()));
//                gmvo.setEntryTime(groupMemberVO.getGroupEntryTime());
//                if (!TextUtils.isEmpty(groupMemberVO.getGuestUserNickAme()))
//                    gmvo.setMemberNickname(groupMemberVO.getGuestUserNickAme());
//                if (!TextUtils.isEmpty(groupMemberVO.getRegisterUserNickAme()))
//                    gmvo.setMemberNickname(groupMemberVO.getRegisterUserNickAme());
//                gmvo.setMemberUserPhoto(groupMemberVO.getUserPhoto());
//                gmvoList.add(gmvo);
//                // 保存群成员资料
//                GroupMemberTable mTable = GroupMemberTable.create(String.valueOf(gvo.getGroupId()), gmvo.getMemberUserId());
//                mTable.setGroupId(String.valueOf(gvo.getGroupId()));
//                mTable.setGroupMemberId(String.valueOf(gmvo.getGroupMemberId()));
//                mTable.setGroupMemberAvatar(gmvo.getMemberUserPhoto());
//                mTable.setGroupMemberUserId(gmvo.getMemberUserId());
//                mTable.setGroupMemberName(gmvo.getMemberNickname());
//                mTable.setGroupMemberType(gmvo.getMemberUserId().equals(gvo.getOwner()) ? 1 : 0);
//                mTable.setUserType(gmvo.getMemberUserType());
//                GroupMemberTable.insertOrUpdate(mTable);
//            }
//            gvo.setGroupMembers(gmvoList);
//
//            ChatContentTable cct = ChatContentTable.queryRowByTargetIdNotNull(String.valueOf(gvo.getGroupId()));
//            cct.setChatType(Canstants.GROUP_CHAT);
//            cct.setTargetId(String.valueOf(gvo.getGroupId()));
//            cct.setTargetName(gvo.getName());
//            cct.setTargetType(gvo.getGroupType());
//            String[] v = GroupMemberTable.getAvatarEntity(String.valueOf(gvo.getGroupId()));
//            if (v != null) {
//                cct.setTargetMemberUserId(v[0]);
//                cct.setTargetAvatarUrl(v[1]);
//            }
//            ChatContentTable.insert(cct);
//        }
        GroupTable groupTable = null;
        GroupMemberTable groupOwnerTable = null;
        if (response.hasRegisteredGroup()) {
            groupTable = getRegisteredGroup(response.getRegisteredGroup());
            List<GroupMemberTable> groupMemberTables = new ArrayList<>();
            if (response.getRegisteredGroupMemberList() != null && !response.getRegisteredGroupMemberList().isEmpty()) {
                for (BusinessProtocolEntities.RegisteredGroupMember registeredGroupMember : response.getRegisteredGroupMemberList()) {
                    GroupMemberTable groupMemberTable = getGroupMemberTable(registeredGroupMember.getGroupMemberId(), registeredGroupMember.getGroupMemberName(), registeredGroupMember.getGroupMemberNick(), registeredGroupMember.getGroupMemberUserId(), registeredGroupMember.getGroupMemberAlias(), registeredGroupMember.getOnlineStatus(), IMSContacts.UserType.REGISTERED_USER, registeredGroupMember.getGroupMemberAvatar(), registeredGroupMember.getGroupMemberType(), groupTable.getGroupId(), groupTable.getGroupName(), groupTable.getGroupType());
                    groupMemberTables.add(groupMemberTable);
                    if (GroupMemberTable.OWNER == registeredGroupMember.getGroupMemberType()) {
                        groupTable.setGroupOwnerId(registeredGroupMember.getGroupMemberUserId());
                        groupOwnerTable = new GroupMemberTable();
                        groupOwnerTable.setGroupMemberUserId(registeredGroupMember.getGroupMemberUserId());
                        groupOwnerTable.setGroupMemberName(registeredGroupMember.getGroupMemberName());
                    }

                }
            }
            insert(groupTable, groupMemberTables);
        } else if (response.hasTouristsGroup()) {
            groupTable = getTouristsGroup(response.getTouristsGroup());
            List<GroupMemberTable> groupMemberTables = new ArrayList<>();
            if (response.getTouristsGroupMemberList() != null && !response.getTouristsGroupMemberList().isEmpty()) {
                for (BusinessProtocolEntities.TouristsGroupMember touristsGroupMember : response.getTouristsGroupMemberList()) {
                    GroupMemberTable groupMemberTable = getGroupMemberTable(touristsGroupMember.getGroupMemberId(), touristsGroupMember.getGroupMemberName(), touristsGroupMember.getGroupMemberNick(), touristsGroupMember.getGroupMemberUserId(), touristsGroupMember.getGroupMemberAlias(), touristsGroupMember.getOnlineStatus(), IMSContacts.UserType.TOURISTS_USER, touristsGroupMember.getGroupMemberAvatar(), touristsGroupMember.getGroupMemberType(), groupTable.getGroupId(), groupTable.getGroupName(), groupTable.getGroupType());
                    groupMemberTables.add(groupMemberTable);
                    if (GroupMemberTable.OWNER == touristsGroupMember.getGroupMemberType()) {
                        groupTable.setGroupOwnerId(touristsGroupMember.getGroupMemberUserId());
                        groupOwnerTable = new GroupMemberTable();
                        groupOwnerTable.setGroupMemberUserId(touristsGroupMember.getGroupMemberUserId());
                        groupOwnerTable.setGroupMemberName(touristsGroupMember.getGroupMemberName());
                    }

                }
            }
            insert(groupTable, groupMemberTables);
        }
        if (null != groupTable) {
//            NotificationUtils.messageNotify(activity);
            NotificationUtils.notifyGroup(activity, groupTable, groupOwnerTable, NotificationHelper.NTYPE_GROUP_INVITE);
            IMSRequester.requestGroupMemberListDontSayHi(groupTable.getGroupId());
        }
        if (isOnScreen) {
            refresh(activity);
        }
    }


    private GroupTable getRegisteredGroup(BusinessProtocolEntities.RegisteredGroup group) {
        GroupTable groupTable = GroupTable.queryRowByGroupIdNotNull(group.getGroupId());
        groupTable.setGroupName(group.getGroupName());
        groupTable.setGroupId(group.getGroupId());
        groupTable.setGroupType(IMSUtils.userTypeAnalysis(group.getGroupId()));//IMSContacts.UserType.REGISTERED_USER
        if (group.hasGroupAnnouncements()) {
            BusinessProtocolEntities.GroupAnnouncements groupS = group.getGroupAnnouncements();
            groupTable.setAnnouncementContent(groupS.getAnnouncementContent());
            groupTable.setAnnouncementTitle(groupS.getAnnouncementTitle());
            groupTable.setAnnouncementId(groupS.getAnnouncementId());
        }
        if (group.hasSettings()) {
            BusinessProtocolEntities.Settings set = group.getSettings();
            groupTable.setSnapchatStatus(set.getSnapchatStatus());
            groupTable.setSnapchatTimeLength(set.getSnapchatTimeLength());
            groupTable.setSnapchatTimeUnit(set.getSnapchatTimeUnit());
        }
        return groupTable;
    }

    private GroupTable getTouristsGroup(BusinessProtocolEntities.TouristsGroup group) {
        GroupTable groupTable = GroupTable.queryRowByGroupIdNotNull(group.getGroupId());

        groupTable.setGroupName(group.getGroupName());
        groupTable.setGroupId(group.getGroupId());
        groupTable.setGroupType(IMSUtils.userTypeAnalysis(group.getGroupId()));//IMSContacts.UserType.TOURISTS_USER
        groupTable.setGroupOwnerId(group.getGroupOwnerUserId());
        if (group.hasGroupAnnouncements()) {
            BusinessProtocolEntities.GroupAnnouncements groupS = group.getGroupAnnouncements();
            groupTable.setAnnouncementContent(groupS.getAnnouncementContent());
            groupTable.setAnnouncementTitle(groupS.getAnnouncementTitle());
            groupTable.setAnnouncementId(groupS.getAnnouncementId());
        }
        if (group.hasSettings()) {
            BusinessProtocolEntities.Settings set = group.getSettings();
            groupTable.setSnapchatStatus(set.getSnapchatStatus());
            groupTable.setSnapchatTimeLength(set.getSnapchatTimeLength());
            groupTable.setSnapchatTimeUnit(set.getSnapchatTimeUnit());
        }
        return groupTable;
    }

    private GroupMemberTable getGroupMemberTable(String groupMemberId, String groupMemberName, String groupMemberNick, String groupMemberUserId, String groupMemberAlias, String onlineStatus, String userType, String groupMemberAvatar, int groupMemberType, String groupId, String groupName, String groupType) {
        GroupMemberTable groupMemberTable = GroupMemberTable.create(groupId, groupMemberUserId);
        groupMemberTable.setGroupMemberId(groupMemberId);
        groupMemberTable.setGroupMemberName(groupMemberName);
        groupMemberTable.setGroupMemberNick(groupMemberNick);
        groupMemberTable.setGroupMemberUserId(groupMemberUserId);
        groupMemberTable.setGroupMemberAlias(groupMemberAlias);
        groupMemberTable.setOnlineStatus(onlineStatus);
        groupMemberTable.setUserType(IMSUtils.userTypeAnalysis(groupMemberUserId));
        groupMemberTable.setGroupMemberAvatar(groupMemberAvatar);
        groupMemberTable.setGroupMemberType(groupMemberType);
        groupMemberTable.setGroupId(groupId);
        groupMemberTable.setGroupName(groupName);
        groupMemberTable.setGroupType(groupType);
        return groupMemberTable;
    }


    @Override
    public void insert(Object... table) {
        super.insert(table);
        try {
            GroupTable groupTable = (GroupTable) table[0];
            List<GroupMemberTable> groupMemberTables = (List<GroupMemberTable>) table[1];
            GroupTable.insert(groupTable);
            if (!groupMemberTables.isEmpty()) {
                GroupMemberTable.insertOrUpdate(groupMemberTables);
            }
            ChatContentTable cct = ChatContentTable.queryRowByTargetIdNotNull(groupTable.getGroupId(), Canstants.GROUP_CHAT);
            cct.setIsTOP(0);
            cct.setChatType(Canstants.GROUP_CHAT);
            cct.setTargetId(groupTable.getGroupId());
            cct.setTargetName(groupTable.getGroupName());
            cct.setTargetType(groupTable.getGroupType());
            cct.setIsSnapchat(groupTable.getSnapchatStatus() ? 1 : 0);
            cct.setUpdateTime(System.currentTimeMillis());
            String[] v = GroupMemberTable.getAvatarEntityLoc(groupTable.getGroupId());
            if (v != null) {
                cct.setTargetMemberUserId(v[0]);
                cct.setTargetAvatarUrl(v[1]);
                cct.setTargetAvatarPath(v[2]);
            }
            cct.setLastMsgType(MsgType.Text);
            cct.setLastMsg(ChatApp.getInstance().getResources().getString(R.string.CREATE_GROUP));
            cct.setIsRead(0);
            ChatContentTable.insert(cct);
            MessageEvent event = MessageEvent.cerateUiRefresh(EventConstants.Action.CHAT_REFRESH);
            UserChatTable u = new UserChatTable(groupTable.getGroupId(), groupTable.getGroupName(), Canstants.GROUP_CHAT, cct.getIsSnapchat() == 1 ? true : false, cct.getLastMsgType(), cct.getLastMsg(), cct.getUpdateTime());
            u.setReceiveType(UserChatTable.RECEIVE_FROM_NET);
            event.setData(new Gson().toJson(u));
            EventBus.getDefault().post(event);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
